package com.zbcz.crm

import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import com.zbcz.crm.adapter.CustomerSelectorAdapter
import com.zbcz.crm.databinding.ActivityUserSelectorBinding
import com.zbcz.crm.util.ToastUtils
import com.zbcz.crm.viewmodel.CustomSelectorViewModel

class CustomerSelectorActivity : BaseActivity() {


    private lateinit var mBinding: ActivityUserSelectorBinding

    private val mViewModel: CustomSelectorViewModel by viewModels()

    companion object {
        const val CUSTOMER_DATA = "CUSTOMER_DATA"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityUserSelectorBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        init()
    }

    private var mAdapter: CustomerSelectorAdapter = CustomerSelectorAdapter()

    private fun init() {
        mViewModel.queryCustomerList(1)
        mBinding.rcList.adapter = mAdapter
        mViewModel.mCustomerLiveData.observe(this) { pagerWrapper ->
            if (pagerWrapper != null) {
                if (pagerWrapper.current == 1) {
                    pagerWrapper.records?.let { it1 -> mAdapter?.submitData(it1) }
                    mViewModel.mCurrentPage = pagerWrapper.current
                } else {
                    if (!pagerWrapper.records.isNullOrEmpty()) {
                        mAdapter.addNextPageData(pagerWrapper.records)
                        mViewModel.mCurrentPage = pagerWrapper.current
                    } else {
                        ToastUtils.show("没有更多数据了")
                    }
                }
            }
            mBinding.refreshLayout.finishLoadMore()
            mBinding.refreshLayout.finishRefresh()
        }
        mBinding.tvConfirm.setOnClickListener {
            val result = mAdapter?.getSelectedCustom()
            if (result == null) {
                ToastUtils.show("请选择客户")
            }
            val intent = Intent()
            intent.putExtra(CUSTOMER_DATA, result)
            setResult(RESULT_OK, intent)
            finish()
        }
        mBinding.editText.addTextChangedListener {
            mAdapter?.filter(it.toString())
        }
        mBinding.tvCancel.setOnClickListener {
            finish()
        }
        mBinding.refreshLayout.setOnRefreshListener {
            mViewModel.queryCustomerList(1)

        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            mViewModel.queryCustomerList(mViewModel.mCurrentPage + 1)
        }
    }
}